<template>
	<view>上传1
		<image-upload :max="1" name="file" :chooseNum="1" v-model="record.check_img" @chooseSuccess="ChooseSuccess"
			@imgDelete="imgDelete">
		</image-upload>
		
		<view @tap="ChooseImage" >上传2：</view>
	</view>
</template>

<script>
	import {
		getOssUploadsParams
	} from '@/common/api.js';
	import imageUpload from '@/components/image-upload/image-upload.vue'
	export default {
		name: 'byImgUpload',
		props: {
			authId: String,
			imgUrl: String,
			deleteFlag: Boolean,
			startShowAction: Function,
			startDelete: Function,
			imgActions: Array
		},
		onShow() {
			this.getdata();
		},
		data() {
			return {
				progress: 0,
				record: {
					check_img: []
				},
				formdata: {
					accessid: '',
					callback: '',
					dir: '',
					expire: '',
					host: '',
					policy: '',
					signature: ''
				}
			}
		},
		methods: {
			//获取oss签名信息
			getdata() {
				getOssUploadsParams().then(res => {
					if (res.code === 2000) {
						this.formdata = res.data;
					}
					console.log(123, this.formdata)
				})
			},
			ChooseSuccess(tempFilePaths) { //选择图片返回
				this.imgUpload(tempFilePaths)
			},
			imgUpload(tempFilePaths) {
				console.log(1233,tempFilePaths)
				let _self = this;
				uni.showLoading({
					title: '上传中'
				});

				let uploadImgs = [];
				tempFilePaths.forEach((item, index) => {
					uploadImgs.push(new Promise((resolve, reject) => {
						/* let str = 'blob:http://localhost:8080/';
						let imgName = '';
						if (item.indexOf(str) > -1) {
							imgName = item.split("blob:http://localhost:8080/")[1]
						} else {
							imgName = item
						} */
						console.log(1234,item)
						let filename = item.tempFilePaths[0];
						let pos = filename.lastIndexOf('.');
						let suffix = '';
						if (pos != -1) {
							suffix = filename.substring(pos);
						}
						let file_name = new Date().getTime() + Math.random().toString(36).substring(3,20) + suffix;
						uni.uploadFile({
							url: _self.formdata.host,
							filePath: filename,
							fileType: 'image',
							name: 'file',
							formData: {
								name: filename,
								'key': _self.formdata.dir + file_name,
								'policy': _self.formdata.policy,
								'OSSAccessKeyId': _self.formdata.accessid,
								'success_action_status': '200',
								//让服务端返回200,不然，默认会返回204
								'signature': _self.formdata.signature,
							},
							success: (res) => {
								console.log('res', res);
								uni.showToast({
									title: '上传成功',
									icon: 'success',
									duration: 1000
								});
								resolve(res);
							},
							fail: (err) => {
								console.log('err',err);
								reject(err);
							}
						});

					}))
				})
				Promise.all(uploadImgs).then((results) => { //执行所有需请求的接口
						uni.hideLoading();
					})
					.catch((res, object) => {
						uni.hideLoading();
					});
			},
			async ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'],
					success: (file_res) => {
						let filename = file_res.tempFilePaths[0]
						let pos = filename.lastIndexOf('.')
						let suffix = ''
						if (pos != -1) {
							suffix = filename.substring(pos)
						}
						let file_name = new Date().getTime() + Math.random().toString(36).substring(3,
							20) + suffix
						getOssUploadsParams().then(res => {
							console.log(123, res)
							let uploadTask = uni.uploadFile({
								url: res.data.host,
								filePath: filename,
								fileType: 'image',
								name: 'file',
								formData: {
									name: filename,
									'key': res.data.dir + file_name,
									'policy': res.data.policy,
									'OSSAccessKeyId': res.data.accessid,
									'success_action_status': '200',
									//让服务端返回200,不然，默认会返回204
									'signature': res.data.signature,
								},
								success: (res) => {
									console.log('uploadImage success, res is:', res)
									uni.showToast({
										title: '上传成功',
										icon: 'success',
										duration: 1000
									});
									//this.$emit('imgUploaded', {data: res.data.host + fileName, authId: this.authId});
								},
								fail: (err) => {
									console.log('uploadImage fail', err);
									uni.showModal({
										content: err.errMsg,
										showCancel: false
									});
								}
							});
							uploadTask.onProgressUpdate((res) => {
								console.log("上传进度" + res.progress);
								this.progress = res.progress;
							});
						})
						//resolve(res)
					}
				})
				// let files = await OSSUtil.getImage(); // 选择图片
				// let sign = await OSSUtil.get_STS() // 获取签名等信息
				// let imageSrc = files.tempFilePaths[0];
				// let fileName = OSSUtil.getFileName(imageSrc); // 自定义上传后的文件名称
				// this.$emit('imgUploaded', {data: files.tempFilePaths[0], authId: this.authId});
			},
		}
	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
	/* @import "../style/function.less";
    @import "../style/variable.less"; */

	.zyby-img-upload-common {
		height: 450rpx;
		width: 100%;
		margin-top: 26rpx;
	}

	.auth-img-item {
		position: relative;

		.exist-img {
			width: 100%;
			height: 100%;
		}

		.upload-progress {
			position: absolute;
			bottom: 0;
			right: 0;
			left: 0;
		}

		.img-delete {
			//.square-hw(36);
			position: absolute;
			top: 10rpx;
			right: 10rpx;
		}
	}

	.img-item-special {
		border: 1px dashed #13DBBF;
		/*no*/
		border-radius: 6rpx;
		/*no*/
	}
</style>
